package com.dcivision.dms.taglib;
/*
 * @(#)UserpickerTag.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */


import java.sql.Connection;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.struts.util.RequestUtils;

import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.taglib.TagUtil;
import com.dcivision.framework.taglib.html.FormTag;
import com.dcivision.framework.taglib.html.TextTag;
import com.dcivision.rules.RuleOperationConstant;
import com.dcivision.user.bean.UserGroup;
import com.dcivision.user.bean.UserRecord;
import com.dcivision.user.bean.UserRole;
import com.dcivision.user.dao.UserGroupDAObject;
import com.dcivision.user.dao.UserRecordDAObject;
import com.dcivision.user.dao.UserRoleDAObject;

/**
 SelectUserTag
 
 <p>This class is to extend the TextTag provided by Apache Struts.<p>
 <p>Modification in "struts-html.tld"<br>
 
 @author          jerry zhou
 @company         DCIVision Limited
 @creation date   08/15/2005
 @version         $Revision: 1.7.2.2 $
 */
public class SelectUserTag extends TextTag {
  
  public static final String REVISION = "$Revision: 1.7.2.2 $";
  
  private String pageFlag = "";  
  private String isMulitple = "";
  private String mulitpleValue = "";
  
  private Integer index = null;
  
  public String getPageFlag() {
    return pageFlag;
  }
  
  public void setPageFlag(String pageFlag) {
    this.pageFlag = pageFlag;
  }
  
  public String getIsMulitple() {
    return isMulitple;
  }
  
  public void setIsMulitple(String isMulitple) {
    this.isMulitple = isMulitple;
  }
  
  public String getMulitpleValue() {
    return mulitpleValue;
  }
  
  public void setMulitpleValue(String mulitpleValue) {
    this.mulitpleValue = mulitpleValue;
  }
  
  
  public Integer getIndex() {
    
    return index;
  }
  
  public void setIndex(Integer index) {
    
    this.index = index;
  }
  /** default constructor
   */
  public SelectUserTag() {
    super();
  }
  
  
  public int doStartTag() throws JspException {
    FormTag formTag = (FormTag)BodyTagSupport.findAncestorWithClass(this, FormTag.class);
    //log.debug("==================="+this.getValue());
    Object valueObj = RequestUtils.lookup(pageContext, name, property, null);
    
    //Object valueObj2 = RequestUtils.lookup(pageContext, name, "showName" + index, null);
    //log.debug("AAAAAAAAAAAAAAAAAAAAAAAAA:"+valueObj2);
    
    String value = null;
    boolean str=true;
    String hiddenName = "criterionHiddenValue";
    String showName = "criterionShowValue";
    String userID = "";
    String groupID = "";
    String roleID = "";
    String passValue = "";
    String passShowValue = "";
    
    if(valueObj instanceof String[]){
      
      if (valueObj==null) {
        value = "";
      } else {
        value = ((String[])valueObj)[0];  
      }
      str=false;
    } else {    
      value = valueObj==null? "": valueObj.toString();
    }
    String sPropertyName = this.getProperty();
    int retValue;
    
    // set the display value
    if ( Utility.isEmpty(value) ) {
      setValue("");
    }else{
      try { 
        //value = TextUtility.replaceString(value,RuleOperationConstant.SPLIT_COMMA,RuleOperationConstant.SPLIT_SEMICOLON);
        String[] splitAry = TextUtility.splitString(value, RuleOperationConstant.SPLIT_COMMA);
        String showValue = "";
        
        int count = 0;
        int passCount = 0;        
        int passShowCount = 0;
        for (int i=0 ; i<splitAry.length ; i++ ){
          String splitStr = splitAry[i];
          if (splitStr.indexOf(RuleOperationConstant.SPLIT_COLON)>-1){
            String[] showAry = TextUtility.splitString(splitStr, RuleOperationConstant.SPLIT_COLON);
            if(!Utility.isEmpty(showAry)){
              
              if(i!=0){
                showValue += RuleOperationConstant.SPLIT_BIAS;
              }
              if (passShowCount !=0){
                passShowValue += RuleOperationConstant.SPLIT_BIAS;
              }
              if (splitStr.indexOf(GlobalConstant.SUBJECT_TYPE_USER)>-1){
                UserRecord record = getUserRecordByID(new Integer(showAry[1]));
                showValue += record.getFullName();
                passShowValue += record.getFullName();
                userID = userID + showAry[1] + ",";
              }else if (splitStr.indexOf(GlobalConstant.SUBJECT_TYPE_GROUP)>-1){
                UserGroup group = getUserGroupByID(new Integer(showAry[1]));
                showValue += group.getGroupName();
                passShowValue += group.getGroupName();
                groupID = groupID + showAry[1] + ",";
              }else if (splitStr.indexOf(GlobalConstant.SUBJECT_TYPE_ROLE)>-1){
                UserRole role = getUserRoleByID(new Integer(showAry[1]));
                showValue += role.getRoleName();
                passShowValue += role.getRoleName();
                roleID = roleID + showAry[1] + ",";
              }
              count ++;
              passShowCount ++;
            }
          }else{
            if (count !=0){
              showValue += RuleOperationConstant.SPLIT_BIAS;
            }
            if (passCount !=0){
              passValue += RuleOperationConstant.SPLIT_BIAS;
            }
            showValue += splitStr;
            passValue += splitStr;
            count ++;
            passCount ++;
          }
        }
        setValue(showValue);
        
      } catch (ApplicationException appEx) {
        throw new JspException(appEx);
      }
    }
    if(!Utility.isEmpty(index)){
      setProperty("dummy_" + sPropertyName + "_" + index);
    }else{
      setProperty("dummy_" + sPropertyName );
    }
//  setOnkeypress("return false;");   // disable keyboard input
//  setOnkeydown("return false;");    // disable keyboard input
    retValue = super.doStartTag();
    setProperty(sPropertyName);
    
    try{
      JspWriter out = pageContext.getOut();
      
      // hidden field
      if(!Utility.isEmpty(index)){
        out.println("<input type='hidden' name='" + hiddenName + index + "' value='" + value + "'>");
        out.println("<input type='hidden' name='" + showName + index + "' value='" + passShowValue + "'>");
      }else{
        out.println("<input type='hidden' name='" + hiddenName  + "' value='" + value + "'>");
        out.println("<input type='hidden' name='" + showName  + "' value='" + passShowValue + "'>");
      }
      
      // show the user picker if it is for editing
      if (!textOnly && !formTag.getTextOnly()) {
        String contextPath = (String)this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);
        String sUrl ="";
        //dms/MaintDmsPopComplex.do
        sUrl = contextPath + "/dms/MaintDmsPopComplex.do?userID="+ userID + "&groupID=" + groupID + "&roleID=" + roleID + "&index=" + this.index + "&passValue=" + passValue;
        
        String sName = "DCIVisionPopupDmsComplexPanel";
        String sPopW = "520";
        String sPopH = "500";
        String sFeature = "scrollbars=yes,resizable=yes";
        
        // <a> tag for displaying the user picker
        out.print(" <a href=\"javascript:void(0);\" onclick=\"return OpenCenteredPopup('" + sUrl + "', '" + sName + "', " + sPopW + ", " + sPopH + ", '" + sFeature + "');\">");
        //print the html img tag for search user image
        out.print(TagUtil.renderImage(pageContext, "IconPopupSearch.gif", true));
        // close the <a> tag
        out.println("</a>");
      }
    } catch (Exception e) {
      throw new JspException(e);
    }
    return retValue;
  }
  
  
  /** create the image path of the search user icon
   * @return the string of the search user icon image path
   * @throws JspException throws JspException
   */
  protected String imgSrc() throws javax.servlet.jsp.JspException {
    String contextPath = (String)this.pageContext.getServletContext().getAttribute(GlobalConstant.CONTEXT_PATH_KEY);
    SessionContainer sessionContainer = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    String preference = SystemParameterFactory.getSystemParameter(SystemParameterConstant.PREFERENCE);
    
    if ((sessionContainer!=null) && (sessionContainer.getUserRecord()!=null)) {
      if (sessionContainer.getUserRecord().getPreference()!=null) {
        preference = sessionContainer.getUserRecord().getPreference().toString();
      }
    }
    return (contextPath+"/theme/pref"+preference+"/img/common/IconPopupSearch.gif");
  }
  
  /** return a user record according to the given id
   *  @param    id
   *  @return   UserRecord
   *  @throws   ApplicationException
   */
  protected UserRecord getUserRecordByID(Integer id) throws ApplicationException {
    SessionContainer sessionCon = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = (Connection)this.pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    UserRecordDAObject dao = new UserRecordDAObject(sessionCon, conn);
    
    try {
      return (UserRecord)dao.getObjectByID(id);
    } catch (ApplicationException appEx) {
      throw appEx;
    }
  }
  
  protected UserGroup getUserGroupByID(Integer id) throws ApplicationException {
    SessionContainer sessionCon = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = (Connection)this.pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    UserGroupDAObject dao = new UserGroupDAObject(sessionCon, conn);
    
    try {
      return (UserGroup)dao.getObjectByID(id);
    } catch (ApplicationException appEx) {
      throw appEx;
    }
  }
  
  protected UserRole getUserRoleByID(Integer id) throws ApplicationException {
    SessionContainer sessionCon = (SessionContainer)this.pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = (Connection)this.pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    UserRoleDAObject dao = new UserRoleDAObject(sessionCon, conn);
    
    try {
      return (UserRole)dao.getObjectByID(id);
    } catch (ApplicationException appEx) {
      throw appEx;
    }
  }
  
}
